package cn.net.lwj.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import org.slf4j.Logger;

public class ConfigUtil {

	//static Logger logg = Logger.getLogger(ConfigUtil.class);

	/** 系统配置容器 */
	private static Properties sysProperties = new Properties();
	static {
		try {
            //当配置文件在外层,如src->main->resource这个目录下时,用上面这个路径访问
			InputStream sysin = ConfigUtil.class.getResourceAsStream("/config.properties");
			//当配置文件在WEB-INF->config这个文件夹下时才通过这种方式获取
			//String path= URLDecoder.decode(new File(ConfigUtil.class.getResource("/").getPath()).getParentFile().getAbsolutePath()+"/config.properties","utf-8");
			//InputStream sysin = new FileInputStream(path);
			if (sysin != null) {
				sysProperties.load(sysin);
			}
		} catch (Exception ioe) {
			throw new RuntimeException(ioe.getMessage());
		}
	}

	@SuppressWarnings("unused")
	private static void readProperties(InputStream in, Properties target) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(in, "GBK"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String tmp = "";
		try {
			int ban = 0;
			String key = "";
			String val = "";
			while ((tmp = reader.readLine()) != null) {
				tmp = tmp.trim();
				if (tmp.indexOf("#") != 0) {
					ban = tmp.indexOf(" ");
					if (ban > -1) {
						key = tmp.substring(0, ban);
						val = tmp.substring(ban + 1, tmp.length());
					} else {
						ban = tmp.indexOf("=");
						if (ban > -1) {
							key = tmp.substring(0, ban);
							val = tmp.substring(ban + 1, tmp.length());
						} else {
							key = tmp;
							val = "";
						}
					}
					target.setProperty(key, val);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				reader.close();
				in.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 获得系统配置信息
	 * 
	 * @param
	 * @return
	 */
	public static String getSystemInfo(String id) {
		String ret = null;
		ret = (String) sysProperties.get(id);
		if ((ret == null) || (ret.length() < 1)) {
			ret = "";
		}
		return ret.trim();
	}

	public static int getSystemInfoInt(String id) {
		String ret = null;
		ret = (String) sysProperties.get(id);
		if ((ret == null) || (ret.length() < 1)) {
			ret = "";
		}
		try {
			return Integer.parseInt(ret.trim());
		} catch (Exception e) {
		}
		return 0;
	}

	public static Long getSystemInfoLong(String id) {
		String ret = null;
		ret = (String) sysProperties.get(id);
		if ((ret == null) || (ret.length() < 1)) {
			ret = "";
		}
		try {
			return new Long(ret.trim());
		} catch (Exception e) {
		}
		return null;
	}
	
	public static int getSystemInfoToInt(String id) {
		String ret = getSystemInfo(id);
		if ((ret == null) || (ret.length() < 1)) {
			return 0;
		} else {
			return Integer.parseInt(ret);
		}
	}

}
